package example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;

@RestController
@RequestMapping("async")
public class AsyncController {


    /**
     * 返回Callable实现的异步处理
     * SpringMVC将callable提交到一个任务执行器TaskExecutor中，使用一个隔离的线程进行执行
     * dispactorServlet和所有filter退出web容器的线程，responce保持打开状态
     * callable返回结果，springmvc将请求重新派发给容器，恢复之前的处理，继续执行视图渲染等工作
     * @return Callable
     */
    @RequestMapping("testasync")
    public Callable<String> test() {
        System.out.println("主线程开始：" + Thread.currentThread());

        Callable<String>callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("子线程开始：" + Thread.currentThread());

                Thread.sleep(5000);

                System.out.println("子线程结束：" + Thread.currentThread());
                return "test";
            }
        };

        System.out.println("主线程结束：" + Thread.currentThread());

        return callable;
    }

    // 保存DeferredResult的队列
    private static Queue<DeferredResult<String>> queue = new ConcurrentLinkedQueue<>();

    // 请求放在队列中，等待处理
    @RequestMapping("testasync2")
    public DeferredResult<String> test2() {
        DeferredResult<String> deferredResult = new DeferredResult<>(3000L,"failed");
        queue.add(deferredResult);
        return deferredResult;
    }

    public void handle() {
        DeferredResult<String> result = queue.poll();
        result.setResult("");
    }


}













